/*
 * Copyright [2009] [Marcin Rzeźnicki]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
package mr.go.yaxc.actions;

import java.util.LinkedList;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.apache.commons.beanutils.MethodUtils;
import org.xml.sax.Attributes;

/**
 * This action calls static method of some class (see <i>name</i> attribute)
 * when processed
 * 
 * <h6>on xml element start:</h6> Sets <i>params</i> <h6>on xml element end:</h6>
 * Calls static method with <i>params</i> as actual arguments, passing result
 * (if not null) to parent's <i>params</i>, or, if <i>id</i> attribute is set,
 * puts it in the global context <h6>prerequisites:</h6> none <h6>attributes:</h6>
 * <table>
 * <tr>
 * <th>Attribute name</th>
 * <th>What is it for?</th>
 * <th>Required?</th>
 * </tr>
 * <tr>
 * <td><i>name</i></td>
 * <td>interpreted as class.methodName (for example
 * com.mypackage.MyClass.staticMethod)</td>
 * <td>yes</td>
 * </tr>
 * <tr>
 * <td><i>id</i></td>
 * <td>if set, puts result of method call (if not null) in global context</td>
 * <td>no</td>
 * </tr>
 * </table>
 *<p>
 * Example:<br>
 * 
 * <pre>
 * &lt;Method name=&quot;mr.go.yaxc.tests.test1.BeanRepository.addBean&quot;&gt;
 * 		&lt;Ref id=&quot;bean&quot; /&gt;
 * 	&lt;/Method&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class CustomCode extends Action {

    private String id;
    private String name;

    @Override
    public void carryOut(String name, Attributes attributes,
                         ScopeHandler handler)
            throws Exception {
        id = attributes.getValue(getAttribute("id"));
        this.name = attributes.getValue(getAttribute("name"));
        if (this.name == null) {
            throw new ConfigurationError("Missing attribute: " + getAttribute(
                    "name"));
        }
        params = new LinkedList<Object>();
    }

    @Override
    public void processed(String body, ScopeHandler handler)
            throws Exception {
        int lastIndexOfDot = name.lastIndexOf('.');
        final String classname = name.substring(0,
                                                lastIndexOfDot);
        final String methodname = name.substring(lastIndexOfDot + 1);
        final Class<?> aClass = Class.forName(classname);
        if (handler.getLogger().isDebugEnabled()) {
            handler.getLogger().debug("Calling method {}({})",
                                      name,
                                      params.toString());
        }
        final Object result = MethodUtils.invokeStaticMethod(aClass,
                                                             methodname,
                                                             params.toArray());
        if (result != null) {
            if (id != null) {
                handler.setReference(id,
                                     result);
                if (handler.getLogger().isDebugEnabled()) {
                    handler.getLogger().debug("Id '{}': {}",
                                              id,
                                              result.toString());
                }
            }
            handler.tryAddParam(result);
        }
    }
}
